#include "caseeditor.h"
#include "ui_caseeditor.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QMap>
#include "widget.h"
#include "network.h"
#include "MessageType.h"
#include "tcpsocketsingleton.h"
#include <QDateTime>
#include <QTime>
#include <QVBoxLayout>

caseeditor::caseeditor(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::caseeditor)
{
    ui->setupUi(this);

    this->setWindowTitle("医生端");
    this->setWindowIcon(QIcon(":doctorimg/img/doctorIcon.png"));

    srand((unsigned int)time(nullptr));

    // 设置主窗口背景及控件样式
    this->setStyleSheet(
        "QWidget { background-color: rgba(255, 240, 245, 0.95); }" // 整体背景为浅粉色
        "QLabel { color: #880E4F; font-size: 24px; font-weight: bold; }" // 增大字体为24px
        "QLineEdit { min-height: 40px; background-color: rgba(255, 255, 255, 0.9); "
        "border: 2px solid #F48FB1; padding: 12px; border-radius: 10px; font-size: 20px; color: black; }" // 调整输入框
        "QPushButton { min-width: 100px; min-height: 40px; background-color: #F8BBD0; color: white; border: 2px solid #F48FB1; "
        "padding: 15px 30px; border-radius: 12px; font-size: 22px; font-weight: bold; }" // 按钮背景、字体及大小设置
        "QPushButton:hover { background-color: #F48FB1; }" // 悬停时按钮背景变深粉色
    );

    // 垂直布局设置
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setAlignment(Qt::AlignCenter); // 垂直布局居中
    mainLayout->setSpacing(20); // 控件间距

    // 添加标题标签
    QLabel *titleLabel = ui->label;
    mainLayout->addWidget(titleLabel, 0, Qt::AlignCenter); // 将标题标签添加到主布局并居中

    // 创建网格布局用于输入框和标签
    QGridLayout *gridLayout = new QGridLayout();
    gridLayout->setSpacing(15); // 控件间距

    // 添加患者姓名、医生姓名、患者ID标签及输入框
    gridLayout->addWidget(ui->label_2, 0, 0); // 患者姓名标签
    gridLayout->addWidget(ui->name, 0, 1); // 患者姓名输入框
    gridLayout->addWidget(ui->label_4, 1, 0); // 医生姓名标签
    gridLayout->addWidget(ui->doctorName, 1, 1); // 医生姓名输入框
    gridLayout->addWidget(ui->label_3, 2, 0); // 患者ID标签
    gridLayout->addWidget(ui->id, 2, 1); // 患者ID输入框

    // 添加病例内容文本框
    gridLayout->addWidget(ui->caseTextEdit, 3, 0, 1, 2); // 文本编辑框占据两列
    mainLayout->addLayout(gridLayout); // 将网格布局添加到主布局

    // 创建按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(ui->loadDataButton); // 添加搜索按钮
    buttonLayout->addWidget(ui->saveButton); // 添加保存按钮
    buttonLayout->addWidget(ui->pushButton); // 添加退出按钮
    mainLayout->addLayout(buttonLayout); // 将按钮布局添加到主布局

    // tcpSocket  = new QTcpSocket;
    // // tcpSocket->connectToHost("127.0.0.1", 12345);
    // if (tcpSocket->state() == QAbstractSocket::UnconnectedState) {
    //     tcpSocket->connectToHost("127.0.0.1", 12345);
    // }

    tcpSocket = TcpSocketSingleton::instance().socket();

    // 断开之前所有连接
    disconnect(tcpSocket, &QTcpSocket::readyRead, nullptr, nullptr);
    tcpSocket->flush();

    // 连接信号槽，处理服务器的响应
    connect(tcpSocket, &QTcpSocket::readyRead, this, [ = ]() {
        ui->caseTextEdit->clear(); // 清空文本编辑器
        qDebug() << "病例表处的逻辑";
        // 读取服务器的响应数据并处理
        QByteArray responseData = tcpSocket->readAll();
        QList<QMap<QString, QString >> responseMap = convertByteArrayToQMapArrayCustom(responseData);

        // 显示服务器响应的数据
        QString responseText;
        for (const QMap<QString, QString>& map : responseMap) {
            for (auto it = map.constBegin(); it != map.constEnd(); ++it) {
                responseText += it.key() + ": " + it.value() + "\n";
            }
            responseText += "\n"; // 添加空行以分隔每个 QMap
        }

        ui->caseTextEdit->setPlainText(responseText);
    });

}

caseeditor::~caseeditor()
{
    delete ui;
}

void caseeditor::on_loadDataButton_clicked()
{
    loadCaseData(); // 加载病例数据
}

void caseeditor::on_saveButton_clicked()
{
    saveCaseData(); // 保存病例数据
}

void caseeditor::loadCaseData()
{
    QString patientId = ui->id->text();
    QString patientName = ui->name->text();

    // 准备查询请求数据
    QMap<QString, QString> data;
    data.insert("type", MEDICIALRECDATABASE);
    data.insert("databaseoperator", QString::number(SELECT));
    data.insert("patientid", patientId);
    data.insert("patientname", patientName);

    // 转换为 QByteArray 并发送
    QByteArray sendData = mapToByteArrayCustom(data);
    tcpSocket->write(sendData);
}

void caseeditor::saveCaseData()
{
    QString patientId = ui->id->text();
    QString updatedCaseDetails = ui->caseTextEdit->toPlainText();
    QString patientname = ui->name->text();
    QString doctorName = ui->doctorName->text();

    // 获取系统当前时间
    QDateTime currentTime = QDateTime::currentDateTime();
    QDate mydata = currentTime.date();
    int year = mydata.year();
    int month = mydata.month();
    int day = mydata.day();
    QTime time = currentTime.time();
    int hour = time.hour();
    int min = time.minute();
    int sec = time.second();
    QString mytime = QString("%1-%2-%3 %4:%5:%6")
                     .arg(year, 2, 10, QChar('0'))
                     .arg(month, 2, 10, QChar('0'))
                     .arg(day, 2, 10, QChar('0'))
                     .arg(hour, 2, 10, QChar('0'))
                     .arg(min, 2, 10, QChar('0'))
                     .arg(sec, 2, 10, QChar('0'));

    // 准备更新请求数据
    QMap<QString, QString> data;
    data.insert("type", MEDICIALRECDATABASE);
    data.insert("databaseoperator", QString::number(INSERT));
    data.insert("patientid", QString::number(1));
    data.insert("patientname", patientname);
    data.insert("doctorname", doctorName);
    data.insert("medic", updatedCaseDetails);
    data.insert("date", mytime);

    // 转换为 QByteArray 并发送
    QByteArray sendData = mapToByteArrayCustom(data);
    tcpSocket->write(sendData);
    QMessageBox::information(this, "保存病历", "保存病历成功");
}

void caseeditor::on_pushButton_clicked()
{
    this->close();
    // Widget *widget = new Widget();
    // widget->show();
}
